﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace TorchView.Game
{
  /// <summary>
  /// A torchlight shared stash file
  /// </summary>
  public sealed class SharedStash
  {
    public string Filename { get; private set; }

    public uint FileVersion { get; set; }
    public Item[] Items { get; set; }

    /// <summary>
    /// Load a Torchlight shared stash file
    /// </summary>
    /// <param name="filename">shared stash file</param>
    /// <returns>The shared stash for the file</returns>
    public static SharedStash Load(string filename)
    {
      SharedStash stash = new SharedStash { Filename = filename };
      BinaryReader reader = null;
      try
      {
        reader = new BinaryReader(new FileStream(filename, FileMode.Open, FileAccess.Read));
        stash.FileVersion = reader.ReadUInt32();
        ReadItems(stash, reader);
      }
      finally
      {
        if (reader != null)
          reader.Close();
      }
      return stash;
    }

    private static void ReadItems(SharedStash stash, BinaryReader reader)
    {
      int itemCount = reader.ReadInt32();
      if (itemCount < 0)
        itemCount = 0;
      Item[] items = new Item[itemCount];
      for (int i = 0; i < itemCount; i++)
        items[i] = Item.Read(reader);
      stash.Items = items;
    }
  }
}
